package com.homelock.common.sequence;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.homelock.common.enumeration.SnowflakeType;

/**
 * @description 包装数据中心的工厂类
 * @author chenmfa
 * @date 2019年1月12日15:53:24
 */
public class SnowflakeFactory {
  private static final long DEFAULT_WORKER_ID = 0L;
  
  private static final Map<String, SnowflakeIdWorker> concurrentHashMap = 
      new ConcurrentHashMap<>();
  
  public static SnowflakeIdWorker getDefaultWorker(){
    return getWorker(DEFAULT_WORKER_ID, SnowflakeType.DEFAULT.getCode());
  }
  
  public static SnowflakeIdWorker getWorker(int workerId, SnowflakeType snowflakeType){
    return getWorker(workerId, snowflakeType.getCode());
  }
  
  private static SnowflakeIdWorker getWorker(long workerId, long datacenterId){
    String key = datacenterId + "_" + workerId;
    if(concurrentHashMap.containsKey(key)){
      return concurrentHashMap.get(key);
    }else{
      SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(workerId, datacenterId);
      SnowflakeIdWorker getValue = concurrentHashMap.putIfAbsent( key , snowflakeIdWorker);
      if(null != getValue){
        return getValue;
      }else{
        concurrentHashMap.put(key, snowflakeIdWorker);
        return snowflakeIdWorker;
      }
    }
  }
}
